package hu.ibm.service;

import hu.ibm.dao.UserDAO;
import hu.ibm.model.User;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
	Logger logger = Logger.getLogger(UserDetailsServiceImpl.class);
	@Autowired
	UserDAO userDAO;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User user = null;
		try {
			user = userDAO.getUserByName(username);
		} catch (Exception e) {

		}
		if (user == null) {
			throw new UsernameNotFoundException("UserAccount for name \""
					+ username + "\" not found.");
		}

		String name = user.getUserName();
		String password = user.getPassword();
		boolean enabled = user.isActive();
		boolean accountNonExpired = user.isActive();
		boolean credentialsNonExpired = user.isActive();
		boolean accountNonLocked = user.isActive();

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		if (user.getRoles() != null) {
			for (String role : user.getRoles().split(";")) {
				authorities.add(new GrantedAuthorityImpl(role));
			}
		}
		
		logger.info("\nusername: " + username +"\npassword: " + password +"\nrole: "+ user.getRoles());
		org.springframework.security.core.userdetails.User springUser = new org.springframework.security.core.userdetails.User(
				name, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);

		return springUser;
	}

}
